/*
 *  Copyright 2009 Allan Lykke Christensen.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package dk.i2m.netbeans.modules.doxia.lexer;

import dk.i2m.netbeans.modules.doxia.jcclexer.AptParserTokenManager;
import dk.i2m.netbeans.modules.doxia.jcclexer.SimpleCharStream;
import dk.i2m.netbeans.modules.doxia.jcclexer.Token;
import org.netbeans.spi.lexer.Lexer;
import org.netbeans.spi.lexer.LexerRestartInfo;
import org.openide.util.Exceptions;

/**
 * Implementation of the NetBeans {@link Lexer}. Connects the NetBeans
 * {@link Lexer} with the JavaCC token manager.
 *
 * @author Allan Lykke Christensen
 */
public class AptLexer implements Lexer<AptTokenId> {

    private LexerRestartInfo<AptTokenId> info;
    private AptParserTokenManager tokenManager;

    /**
     * Creates a new instance of the {@link AptLexer}.
     *
     * @param info
     *          {@link LexerRestartInfo}
     */
    AptLexer(LexerRestartInfo<AptTokenId> info) {
        this.info = info;
        SimpleCharStream stream = new SimpleCharStream(info.input());
        tokenManager = new AptParserTokenManager(stream);

    }

    /**
     * Obtains the next valid {@link org.netbeans.api.lexer.Token}.
     *
     * @return Next valid {@link org.netbeans.api.lexer.Token}.
     */
    public org.netbeans.api.lexer.Token<AptTokenId> nextToken() {
        try {
            Token token = tokenManager.getNextToken();
            if (info.input().readLength() < 1) {
                return null;
            }
            return info.tokenFactory().createToken(AptLanguageHierarchy.getToken(
                    token.kind));
        } catch (Throwable err) {
            Exceptions.printStackTrace(err);
            if (info.input().readLength() < 1) {
                return null;
            }
            return info.tokenFactory().createToken(AptLanguageHierarchy.getToken(
                    AptToken.ERROR.id));
        }
    }

    public Object state() {
        return null;
    }

    public void release() {
    }
}
